<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商城</el-breadcrumb-item>
      <el-breadcrumb-item>商城信息列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="filter-container" shadow="never" style="margin-top: 30px;">
      <div style="margin-top: 15px;">
        <i class="el-icon-search"></i>
        <span>筛选搜索</span>
        <el-button type="primary" @click="showCateDialog" style="float: right;">
          添加
        </el-button>
        <el-form :inline="true" size="small" label-width="140px">
          <el-form-item label="输入搜索：">
            <el-input
              class="input-width"
              placeholder="分类名称"
              v-model="input"
              clearable
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

      <el-card class="operate-container" shadow="never">
        <i class="el-icon-tickets"></i>
        <span>数据列表</span>
      </el-card>
<el-table
      :data="
       tables
      "
      highlight-current-row
      v-loading="listLoading"
      style="width: 100%"
       show-index
    
     row-key="id"
      :tree-props="{ children: 'children',children: 'children'}"
      border=""
    >
        <el-table-column prop="id" label="#"></el-table-column>
      <el-table-column prop="catagoryName" label="分类名称"></el-table-column>

       <!-- 排序 -->
      <el-table-column prop="order" label="排序">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.order === '1'">一级</el-tag>
          <el-tag type="success" v-else-if="scope.row.order === '2'">
            二级
          </el-tag>
          <el-tag type="warning" v-else>三级</el-tag>
        </template>
      </el-table-column>
      
      <el-table-column label="操作">
        <template scope="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            circle
            @click="handleEdit(scope.$index, scope.row)"
          ></el-button>
          <el-button
            type="danger"
            icon="el-icon-delete"
            circle
            @click="handleDel(scope.$index, scope.row)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>



     
    
   

    <!-- 添加分类对话框 -->
    <el-dialog title="添加分类" :visible.sync="addCateDialogVisible">
      <!-- 添加分类的表单 -->
      <el-form
        :model="addCateForm"
        ref="addCateFormRef"
        :rules="addCateFormRules"
        label-width="100px"
      >
        <el-form-item label="分类名称:" prop="catagoryName">
          <el-input v-model="addCateForm.catagoryName"></el-input>
        </el-form-item>
        <el-form-item label="父级分类:">
          <el-cascader
            :options="tableData"
            v-model="selectedKeys"
            :props="{
              value: 'id',
              label: 'catagoryName',
              children: 'children',
              checkStrictly: true,
            }"
            clearable
            @change="parentCateChanged"
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCateclick">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑分类名称 -->
    <el-dialog
      title="编辑分类名称"
      :visible.sync="dialogFormVisible"
      width="600px"
    >
      <el-form ref="form" :model="form" :rules="addCateFormRules">
        <el-form-item
          label="分类名称"
          :label-width="formLabelWidth"
          prop="catagoryName"
        >
          <el-input v-model="form.catagoryName" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirm('form')">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 分页组件 -->
    <div class="block">
      <el-pagination
        @size-change="handlePageSizeChange"
        @current-change="handlePageIndexChange"
        :current-page="pager.pageIndex"
        :page-size="pager.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pager.rowsTotal"
        background
      ></el-pagination>
    </div>
  </div>
</template>

<script>
import {getList,addCate, modCate, deleteCate } from '../../api/cate'

export default {
  data() {
    return {
      formLabelWidth: '120px',
      //搜索
      input: '',
      pager: {
        pageIndex: 1,
        pageSize: 10,
        rowsTotal: 30,
      },

      //子级
      parentCateList: {},
      addCateDialogVisible: false,
      // 添加分类表单数据对象
      addCateForm: {
        // 将要添加的分类名称
        catagoryName: '',
        // 父级分类的id
        parentId: 0,
        // 分类的等级，默认要添加的是1一级分类
        order: '1',
      },
      dialogFormVisible: false,
      form: {
        catagoryName: '',
        id: 0,
        newIndex: 0,
      },
      listLoading: false,
      // 表格数据
      tableData: [
        {
          id: 1,
          catagoryName: "CPU",
          children: [
            {
              id: 3,
              catagoryName: "CPU",
            },
          ],
        },
        {
          id: 2,
          catagoryName: "CPU",
          children: [
            {
              id: 4,
              catagoryName: "CPU",
            },
          ],
        },

      ],
      selectedKeys: {},
      addCateFormRules: {
        catagoryName: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
        ],
      },
    }
  },
  computed: {
    tables() {
      const input = this.input
      if (input) {
        console.log('input输入的搜索内容：' + this.input)
        return this.tableData.filter((data) => {
          return data.catagoryName.includes(this.input)
        })
      }

      return this.tableData
    },
  },
    mounted() {
    getList().then(({ data }) => {
      this.tableData = data;
    });
  },

  methods: {
 


    // getRowKeys(row){
    //   return row.code+row.type
    // },
    parentCateChanged(values) {
      console.log(values)
      // 如果selectedKeys数组中的length大于0，证明选中的父级分类
      if (this.selectedKeys.length > 0) {
        // 父级分类的ID
        this.addCateForm.parentId = this.selectedKeys[
          this.selectedKeys.length - 1
        ]
        // 为当前分类的等级赋值
        this.addCateForm.order = this.selectedKeys.length + 1
        // eslint-disable-next-line no-useless-return
        return
      } else {
        // 父级分类的id
        this.addCateForm.parentId = 0
        // 为当前分类的等级赋值
        this.addCateForm.order = 1
      }
    },
    //添加
    showCateDialog() {
      this.addCateDialogVisible = true
    },
    // 提交添加分类
    addCateclick() {
      this.$refs.addCateFormRef.validate((valid) => {
        if (valid) {
          this.addCateForm.order+=''
          addCate(this.addCateForm).then((data) => {
            console.log(data)
            if (data.code == 1000) {
              let obj = data  
              console.log(obj)
              if (obj.order != 1) {
                let newArr = this.tableData
                this.a(newArr, obj)
              } else {
                this.tableData.push(obj)
              }
                 this.$message.success(data.msg)
            } else {
              this.$message.error(data.msg)
            }

            this.addCateDialogVisible = false
            this.addCateForm = {}
          })
        } else {
          this.$message.error('该空不能为空，请填写完毕重新提交')
        }
      })
    },
    a(arr, obj) {
      if (arr != null) {
        try {
          arr.forEach((item) => {
            if (item.id == obj.parentId) {
              if (item.children == null) {
                item.children = []
                item.children.push(obj)
              } else {
                item.children.push(obj)
              }
              throw new Error('EndIterative')
            } else {
              this.a(item.children, obj)
            }
          })
        } catch (e) {
          if (e.message != 'EndIterative') throw e
        }
      } else {
        console.log('看看就好..')
      }
    },
    handleEdit(index, row) {
      this.form.catagoryName = row.catagoryName;
      this.form.id = row.id;

      this.form.newIndex = index;
      this.dialogFormVisible = true
    },
    // 修改分类名称
    confirm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          modCate(this.form.id, this.form).then(({ data }) => {
            this.tableData.splice(this.form.newIndex, 1, data)
            this.dialogFormVisible = false
            this.$message.success('修改成功')
          })
        } else {
          this.$message.error('该空不能为空，请填写完毕重新提交')
        }
      })
    },
    handleDel(index, row) {
      deleteCate(row.id).then((data) => {
        this.tableData.splice(index, 1)
        this.$message.success(data.msg)
      })
    },
    // 页面页码改变时，重新拉取数据
    handlePageIndexChange(val) {
      console.log(val)
      this.pager.pageIndex = val > 0 ? val : 1
      this.fetchData(this.pager)
    },
    // 页面大小改变时，重新拉取数据
    handlePageSizeChange(val) {
      console.log(val)
      this.pager.pageSize = val
      this.fetchData(this.pager)
    },

    
    // 拉取后台数据（带分页）
    // fetchData(pager) {
    //   getList(pager).then((data) => {
    //     console.log(data)

    //     this.tableData = data.data.data
    //     console.log(this.tableData)
    //     this.pager = data.data.pager
    //   })
    // },
  },
}
</script>

<style></style>
